package admin

import (
	"github.com/mars/internal/admin/core/infrastructure/wxcloud"
	"github.com/mars/internal/admin/options"
	"github.com/mars/internal/pkg/gins"
	"github.com/mars/pkg/httpclient"
	"github.com/mars/pkg/shutdown"
)

type AdminServer struct {
	gs *shutdown.GracefulShutdown

	server *gins.GenericAPIServer
}

func createAdminSever(opts *options.Options) (*AdminServer, error) {
	var server AdminServer
	// 创建优雅关闭实例
	server.gs = server.initGracefulShutdown()

	server.server = opts.GinOptions.New()

	gins.InitGenericAPIServer(server.server)
	wxcloudFactory, _ := wxcloud.GetWxCloudFactory(opts.WxcloudOptions, httpclient.NewHttpClient())
	initRouter(server.server.Engine, wxcloudFactory)

	return &server, nil

}

func (s *AdminServer) PrepareRun() *AdminServer {
	s.gs.AddShutdownCallback(shutdown.ShutdownFunc(func(string) (string, error) {
		s.server.Shutdown()
		return "server", nil
	}))

	return s
}

func (s *AdminServer) Run() error {
	go s.server.Run()

	return s.gs.Start()
}

func (s *AdminServer) initGracefulShutdown() *shutdown.GracefulShutdown {
	gs := shutdown.New()
	gs.AddShutdownManager(shutdown.NewPosixSignalManager())
	return gs
}
